package edu.buaa.resourceManager.vo;

import com.google.common.io.ByteStreams;
import edu.buaa.resourceManager.helper.Utils;
import org.slf4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.rmi.CORBA.Util;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by song on 2017/6/4 0004.
 */
public class EZProjectFileOld extends EZProjectFile
{
    private static Logger log = Utils.getDevLogger();

    EZProjectFileOld(ZipFile zipFile) throws IOException {
        for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            log.debug(entry.getName());
            if(entry.getName().toUpperCase().endsWith(".EPJ")){
                extractComment(zipFile.getInputStream(entry));
            }else if(entry.getName().toUpperCase().endsWith(".EWS")){
                extractMaterial(zipFile.getInputStream(entry));
            }
        }
        zipFile.close();
    }

    @Override
    protected void extractComment(InputStream extra) {
        try {
            ByteBuffer in = ByteBuffer.wrap(ByteStreams.toByteArray(extra)).asReadOnlyBuffer().order(ByteOrder.LITTLE_ENDIAN);
            while(true) {
                readUntil(in, b("D9 29 61 FD 1C 9F 28 43 A2 77 78 01 81 55 73 8E"));//
                readUntil(in, b("00 00 00 01 00 00 00 15 02 05 20"));
                long currentFramePos = getFramePos(in);
                int commentLen = getCommentLen(in);
                String comment = readComment(in, commentLen);
//                log.debug("framePos:{} {} len:{}", currentFramePos, comment, commentLen);
                this.comments.put(currentFramePos, comment);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (EZProjectFile.NotFoundException ignore) {

        }
    }

    private String readComment(ByteBuffer in, int commentLen) {
        byte[] content = new byte[commentLen];
        in.get(content);
        return new String(content, Charset.forName("UTF-16LE"));
    }

    private int getCommentLen(ByteBuffer in) throws EZProjectFile.NotFoundException {
        readUntil(in, b("0A 25 65 16 E0 0F 2C 46 85 10 E7 25 80 07 8A 9E"));
        int raw = in.getInt();
//        Utils.getDevLogger().debug("{}", raw);
        return raw - 2;
    }

    private long getFramePos(ByteBuffer in) throws EZProjectFile.NotFoundException {
        //                log.debug("position: {}", in.position());
//                log.debug("{} {} {}", in.get(in.position()), in.get(in.position()+1), in.get(in.position()+2));
        return in.getInt();
    }

    @Override
    protected byte[] b(String hex) {
        String s = hex.replace(" ","");
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    @Override
    protected void extractMaterial(InputStream inputStream)  {
        try{
            ByteBuffer in = ByteBuffer.wrap(ByteStreams.toByteArray(inputStream)).asReadOnlyBuffer().order(ByteOrder.LITTLE_ENDIAN);
            while(true) {
                readUntil(in, b("0A 25 65 16 E0 0F 2C 46 85 10 E7 25 80 07 8A 9E"));
                int pos = in.position();
                int materialPathLen = in.getInt() - 2;
                byte[] content = new byte[materialPathLen];
                in.get(content);
                int start = in.position();
                try {
                    readUntil(in, b("00 00 FF FF FF FF 00 00 00 00 00 00 00 00"));
                    if((in.position() - start)==14){
                        String materialPath = new String(content, Charset.forName("UTF-16LE"));
//                        Utils.getDevLogger().debug("material: {}", materialPath);
                        this.materials.add(materialPath);
                    }else{
                        in.position(pos);
                    }
                }catch (NotFoundException e){
                    in.position(pos);
                }



            }
        }catch (IOException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (EZProjectFile.NotFoundException ignore) {

        }
    }
}
